package com.ruoyi.web.controller.app;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.HttpUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;


/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping(value = "/app")
public class AppController extends BaseController {


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IReportInfoService reportInfoService;

    @Autowired
    private IDriveInfoService driveInfoService;

    @Autowired
    private IEscortService escortService;

    @Autowired
    private IVehicleService iVehicleService;

    @Autowired
    private IAppVersionService iAppVersionService;

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private ICarPositionService carPositionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IStatusLogService statusLogService;

    @Autowired
    private IVehicleBlacklistService vehicleBlacklistService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${appId}")
    private String appId;

    @Value("${appSecret}")
    private String appSecret;

    @Value("${positionServer}")
    private String positionServer;

    /**
     * 提交审核
     *
     * @return
     * @throws IOException
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @RequestMapping("submitAudit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getCode(@RequestBody ReportInfo reportInfo) throws IOException {
        reportInfo.setId(IdUtil.simpleUUID());
        LoginUser loginUser = getLoginUser();

        Date yuyueComeTime = reportInfo.getComeTime();
        Date yuyueOutTime = reportInfo.getOutTime();

        ReportInfo reportInfo1 = new ReportInfo();
        reportInfo1.setCarNumber(reportInfo.getCarNumber());
        List<ReportInfo> reportInfos = reportInfoService.selectReportInfoList(reportInfo1);
        int status = 0;
        for (int i = 0;i<reportInfos.size();i++){
           Date comeTime = reportInfos.get(i).getComeTime();
           Date outTime = reportInfos.get(i).getOutTime();
           Boolean b = false;
           try {
               b = isOverlap(comeTime,outTime,yuyueComeTime,yuyueOutTime);
           }catch (Exception e){}
           if(b){
               status = 1;
           }
        }

//        if(status == 1){
//            return AjaxResult.error("您已预约该时间段，请重新选择日期");
//        }

        /**
         * 创建时间
         */
        reportInfo.setState("0");
        reportInfo.setCreateTime(new Date());
        reportInfo.setLoginId(String.valueOf(loginUser.getUserId()));


        // 驾驶证信息
        DriveInfo driveInfo = new DriveInfo();
        driveInfo.setDriveId(IdUtil.simpleUUID());
        driveInfo.setLoginId(String.valueOf(loginUser.getUserId()));
        driveInfo.setDriveCardId(reportInfo.getDriveCardId());
        driveInfo.setDriveName(reportInfo.getDriveName());
        driveInfo.setDrivePhone(reportInfo.getPhone());
        driveInfo.setReportId(reportInfo.getId());
        // 新增驾驶人id
        driveInfoService.insertDriveInfo(driveInfo);

        // 押运员信息
        Escort escort = new Escort();
        escort.setId(IdUtil.simpleUUID());
        escort.setEscortCardId(reportInfo.getEscortCardId());
        escort.setEscortName(reportInfo.getEscortName());
        escort.setLoginId(reportInfo.getLoginId());
        escort.setReportId(reportInfo.getId());
        escortService.insertEscort(escort);

        // 车辆信息
        Vehicle vehicle = new Vehicle();
        vehicle.setId(IdUtil.simpleUUID());
        vehicle.setCarCompany(reportInfo.getCarCompany());
        vehicle.setCarNumber(reportInfo.getCarNumber());
        vehicle.setDrivingLicenseCard(reportInfo.getDrivingLicenseCard());
        vehicle.setMaxLoad(reportInfo.getMaxLoad());
        vehicle.setLoginId(reportInfo.getLoginId());
        iVehicleService.insertVehicle(vehicle);
        reportInfo.setHpage("0");
        return AjaxResult.success(reportInfoService.insertReportInfo(reportInfo));
    }


    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static boolean isOverlap(Date leftStartDate, Date leftEndDate, Date rightStartDate, Date rightEndDate) {
//        Date leftStartDate = null;
//        Date leftEndDate = null;
//        Date rightStartDate = null;
//        Date rightEndDate = null;
//        try {
//            leftStartDate = format.parse(startdate1);
//            leftEndDate = format.parse(enddate1);
//            rightStartDate = format.parse(startdate2);
//            rightEndDate = format.parse(enddate2);
//        } catch (ParseException e) {
//            return false;
//        }

        return
                ((leftStartDate.getTime() >= rightStartDate.getTime())
                        && leftStartDate.getTime() < rightEndDate.getTime())
                        ||
                        ((leftStartDate.getTime() > rightStartDate.getTime())
                                && leftStartDate.getTime() <= rightEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() >= leftStartDate.getTime())
                                && rightStartDate.getTime() < leftEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() > leftStartDate.getTime())
                                && rightStartDate.getTime() <= leftEndDate.getTime());

    }


    /**
     * 查看登陆人预约的信息
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("getMyAppointmentInformation")
    public AjaxResult getMyAppointmentInformation(ReportInfo reportInfo) throws IOException {
        LoginUser loginUser = getLoginUser();
        /**
         * 根据我的登录信息查看我的预约信息
         */
        reportInfo.setLoginId(String.valueOf(loginUser.getUserId()));
        return AjaxResult.success(reportInfoService.selectReportInfoList(reportInfo));
    }


    /**
     * app登录
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("login")
    public AjaxResult Login(@RequestBody LoginBody loginBody) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * app  后台查看所有申请信息
     * status -1 为所有、 0为未审核、1为审核通过、2为审核未通过、3为已取消预约、
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("getAllAppointmentInformation")
    public AjaxResult getAllAppointmentInformation(String status) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        // 获取所有申请信息
        ReportInfo reportInfo = new ReportInfo();
        if (!Objects.equals("-1", status)) {
            //  0为未审核、1为审核成功、2为审核失败
            reportInfo.setState(status);
        }
        ajax.put("data", reportInfoService.selectReportInfoList(reportInfo));
        return ajax;
    }


    /**
     * app  后台查看所有申请信息
     * id
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("getAppointmentInfoById")
    public AjaxResult getAppointmentInfoById(@RequestBody ReportInfo reportInfo) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        // 获取所有申请信息
        ajax.put("data", reportInfoService.selectReportInfoById(reportInfo.getId()));
        return ajax;
    }


    @RequestMapping("getDriverSLicenseInfo")
    public TableDataInfo getDriverSLicenseInfo(@RequestBody DriveInfo driveInfo) {
        startPage();
        List<DriveInfo> list = driveInfoService.selectDriveInfoList(driveInfo);
        return getDataTable(list);
    }


    @RequestMapping("delDriverSLicenseInfo")
    public AjaxResult delDriverSLicenseInfo(@RequestBody DriveInfo driveInfo) {
        return AjaxResult.success(driveInfoService.deleteDriveInfoByDriveId(driveInfo.getDriveId()));
    }


    @RequestMapping("insertDriverSLicenseInfo")
    public AjaxResult insertDriverSLicenseInfo(@RequestBody DriveInfo driveInfo) {
        driveInfo.setDriveId(IdUtil.simpleUUID());
        return AjaxResult.success(driveInfoService.insertDriveInfo(driveInfo));
    }


    @RequestMapping("/getEscortInfo")
    public TableDataInfo list(@RequestBody Escort escort) {
        startPage();
        List<Escort> list = escortService.selectEscortList(escort);
        return getDataTable(list);
    }


    @RequestMapping("/delEscortInfo")
    public AjaxResult delEscortInfo(@RequestBody Escort escort) {
        return AjaxResult.success(escortService.deleteEscortById(escort.getId()));
    }

    @RequestMapping("/insertEscortInfo")
    public AjaxResult insertEscortInfo(@RequestBody Escort escort) {
        escort.setId(IdUtil.simpleUUID());
        return AjaxResult.success(escortService.insertEscort(escort));
    }


    /**
     * 车辆信息
     */

    @RequestMapping("/insertVehicleInfo")
    public AjaxResult insertVehicleInfo(@RequestBody Vehicle vehicle) {
        vehicle.setId(IdUtil.simpleUUID());
        return AjaxResult.success(iVehicleService.insertVehicle(vehicle));
    }


    @RequestMapping("/delVehicleInfo")
    public AjaxResult delVehicleInfo(@RequestBody Vehicle vehicle) {
        return AjaxResult.success(iVehicleService.deleteVehicleById(vehicle.getId()));
    }


    @RequestMapping("/getVehicleInfo")
    public TableDataInfo getVehicleInfo(@RequestBody Vehicle vehicle) {
        startPage();
        List<Vehicle> list = iVehicleService.selectVehicleList(vehicle);
        return getDataTable(list);
    }


    @RequestMapping("/getYiQing")
    public AjaxResult getYiQing(ReportInfo reportInfo) {
        String url = "https://ditu.so.com/app/yiqing/policy?from=" + reportInfo.getOriginPlace();
        String s = HttpRequest.get(url)
                .header("origin", "http://ditu.so.com")
                .header("accept", "*/*")
                .header("accept-encoding", "gzip, deflate, br")
                .header("accept-language", "zh-CN")
                .header("connection", "keep-alive")
                .execute().body();
        return AjaxResult.success(s);
    }


    /**
     * 获取app版本
     *
     * @return
     */
    @RequestMapping("version")
    public AjaxResult version() {
        AppVersion appVersion = new AppVersion();
        return AjaxResult.success(iAppVersionService.selectAppVersionList(appVersion));
    }


    /**
     * 修改app版本
     *
     * @return
     */
    @RequestMapping("updateVersion")
    public AjaxResult edit(@RequestBody AppVersion appVersion) {
        return toAjax(iAppVersionService.updateAppVersion(appVersion));
    }


    @RequestMapping("updateInfoStatus")
    public AjaxResult updateInfoStatus(@RequestBody ReportInfo reportInfo) {
        ReportInfo reportInfo1 = new ReportInfo();
        AjaxResult ajaxResult = null;
        ajaxResult = httpUtil.reserveSpace(reportInfo);
        Object object = ajaxResult.get("data");
        Object object1 = JSONObject.parseObject(String.valueOf(object)).get("data");


        if(!Objects.equals(object1,"")) {
            String keepTime = JSONObject.parseObject(String.valueOf(object1)).getString("keepTime");
            String orderNo = JSONObject.parseObject(String.valueOf(object1)).getString("orderNo");
            reportInfo.setKeepTime(strToDateLong(keepTime));
            reportInfo.setOrderNo(orderNo);
        }

        reportInfoService.updateReportInfo(reportInfo);

        reportInfo1.setId(reportInfo.getId());
        reportInfo1.setExamineTime(new Date());
        reportInfo1.setState(reportInfo.getState());
        reportInfo1.setExamineOpinion(reportInfo.getExamineOpinion());
        reportInfo1.setReserveType(reportInfo.getReserveType());
        reportInfo1.setReserveId(reportInfo.getReserveId());
        reportInfo1.setReserveName(reportInfo.getReserveName());


        ReportInfo reportInfo2 = reportInfoService.selectReportInfoById(reportInfo.getId());
        SysUser user2 = SecurityUtils.getLoginUser().getUser();
        StatusLog statusLog = new StatusLog();
        statusLog.setId(IdUtil.simpleUUID());
        statusLog.setReasonDeactivation(reportInfo2.getReasonDeactivation());
        statusLog.setOperationId(user2.getUserId().toString());
        statusLog.setReportId(reportInfo2.getId());
        statusLog.setCreateTime(new Date());
        statusLog.setOperation(reportInfo2.getState());
        statusLogService.insertStatusLog(statusLog);

        return AjaxResult.success();
    }

    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    @RequestMapping(value = "h5Save")
    public AjaxResult h5Save(@RequestBody ReportInfo reportInfo) {
        reportInfo.setId(IdUtil.simpleUUID());
        reportInfo.setHpage("1");
        return toAjax(reportInfoService.insertReportInfo(reportInfo));
    }


    @RequestMapping(value = "addGps")
    public AjaxResult addGps(@RequestBody String msg) {
        msg = URLDecoderString(msg);
        if (msg.contains("=")) {
            msg = msg.replace("=", "");
            JSONObject json = (JSONObject) JSON.parse(msg);
            String loginId = String.valueOf(json.get("loginId"));
            JSONObject location = (JSONObject) json.get("location");
            String latitude = String.valueOf(location.get("latitude"));
            String longitude = String.valueOf(location.get("longitude"));
            System.out.println(loginId);
            System.out.println(latitude);
            System.out.println(longitude);
            CarPosition carPosition = new CarPosition();
            carPosition.setId(IdUtil.simpleUUID());
            carPosition.setLoginId(loginId);
            carPosition.setLatitude(latitude);
            carPosition.setLongitude(longitude);
            carPosition.setCreateTime(new Date());
            carPositionService.insertCarPosition(carPosition);

//            if(StringUtils.isNotEmpty(loginId)){
//                List<ReportInfo> reportInfoList = reportInfoService.queryInfoByLoginId(loginId);
//                if(reportInfoList.size()>0){
//                    JSONObject params = new JSONObject();
//                    params.put("appKey",appId);
//                    params.put("appSecret",appSecret);
//                    JSONArray js = new JSONArray();
//                    JSONObject car = new JSONObject();
//                    car.put("plateNo",reportInfoList.get(0).getCarNumber());
//                    car.put("lng",longitude);
//                    car.put("lat",latitude);
//                    car.put("time",sdf.format(new Date()));
//                    js.add(car);
//                    params.put("data",js);
//                    String res = HttpRequest.post(positionServer)
//                            .header(Header.CONTENT_TYPE,"application/json;charset=utf-8")
//                            .body(params.toJSONString())
//                            .execute().body();
//                    System.out.println(params.toJSONString()+"-----"+res);
//                }
//            }
        }
        return AjaxResult.success(msg);
    }


    @RequestMapping(value = "getAllGps")
    public AjaxResult getAllGps() {
        List<CarPositionReportInfo> list = carPositionService.getAll();
        return AjaxResult.success(list);
    }

    @RequestMapping(value = "getAllPoint")
    public AjaxResult getAllPoint() {
        List<CarPositionReportInfo> list = carPositionService.getAllPoint();
        return AjaxResult.success(list);
    }


    // 取消预约
    @RequestMapping(value = "removeyuyue")
    public AjaxResult removeyuyue(@RequestBody ReportInfo reportInfo) {

        ReportInfo reportInfoOld = reportInfoService.selectReportInfoById(reportInfo.getId());

        // 创建时间
        reportInfo.setCreateTime(null);
        // login_id
        reportInfo.setLoginId(null);
        // 状态
        reportInfo.setState(null);
//        hpage
        reportInfo.setHpage(null);
        // 修改时间
        reportInfo.setUpdateTime(new Date());
        reportInfo.setState("3");
        try {
            httpUtil.cancelReserveSpace(reportInfoOld);
            reportInfoService.clearReportInfo(reportInfo);
        } catch (Exception e) {
            logger.info("取消预约车位接口报错", e);
        }
        if (reportInfoService.updateReportInfo(reportInfo) > 0) {
            return AjaxResult.success(1);
        } else {
            return AjaxResult.success(0);
        }
    }


    // 修改预约
    @RequestMapping(value = "updateyuyue")
    public AjaxResult updateyuyue(@RequestBody ReportInfo reportInfo) {
        // 创建时间
        reportInfo.setCreateTime(null);
        // login_id
        reportInfo.setLoginId(null);
        // 状态
        reportInfo.setState(null);
//        hpage
        reportInfo.setHpage(null);
        // 修改时间
        reportInfo.setUpdateTime(new Date());

        return AjaxResult.success(reportInfoService.updateReportInfo(reportInfo));
    }


    @RequestMapping(value = "selectReportInfoListLike")
    public TableDataInfo selectReportInfoListLike(@RequestBody ReportInfo reportInfo) {
        startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<ReportInfo> list = reportInfoService.selectReportInfoListLike(reportInfo);
        for (int i = 0; i < list.size(); i++) {
            if (pageNum == null) {
                pageNum = 1;
            }
            if (pageSize == null) {
                pageSize = list.size();
            }
            list.get(i).setSerialNumber(String.valueOf(((pageNum - 1) * pageSize) + (i + 1)));
        }
        return getDataTable(list);
    }


    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String URLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping(value = "addUser")
    public AjaxResult add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("用户已存在");
        }
        String captcha = redisCache.getCacheObject(user.getUserName());
        if(!captcha.contains(user.getCode())){
            return AjaxResult.error("验证码错误");
        }
        user.setPhonenumber(user.getUserName());
        Long[] roles = new Long[]{Long.parseLong("101")};
        user.setRoleIds(roles);
        user.setRoleId(Long.parseLong("101"));
        user.setCreateBy("注册");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }


    @RequestMapping("/getDeptList")
    public AjaxResult getDeptList() {
        List<SysDept> list = deptService.getDeptList();
        return AjaxResult.success(list);
    }

    /**
     * app 获取 黑名单
     * @return
     */
    @RequestMapping(value = "getVehicleBlacklistList")
    public AjaxResult getVehicleBlacklistList(){
        VehicleBlacklist vehicleBlacklist = new VehicleBlacklist();
        List<VehicleBlacklist> list = vehicleBlacklistService.selectVehicleBlacklistList(vehicleBlacklist);
        return AjaxResult.success(list);
    }

    @RequestMapping(value = "getVehicleBlacklistListPublic")
    public AjaxResult getVehicleBlacklistListPublic(){
        VehicleBlacklist vehicleBlacklist = new VehicleBlacklist();
        List<VehicleBlacklist> list = vehicleBlacklistService.selectVehicleBlacklistList(vehicleBlacklist);
        return AjaxResult.success(list);
    }


    @RequestMapping(value = "/userIdLogout/{userId}")
    public AjaxResult userIdLogout(@PathVariable(value = "userId", required = false) Long userId){
        Long[] userIds = {userId};
        if (!ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

}
